/*
 * @Author: duapple
 * @Date: 2021-09-13 08:30:36
 * @LastEditTime: 2021-11-30 08:49:37
 * @LastEditors: duapple
 * @Description: Add description
 * @FilePath: /app_start/main.go
 * Copyright (c) 2011 duapple - All rights reserved.
 */
package main

import (
	"fmt"
	"os/exec"
	"path/filepath"
	"runtime"
	"time"

	file "gitee.com/duapple/go_config_file"
)

type AppInfo struct {
	Cmd         string
	Args        []string /** 参数列表 */
	StartDelay  uint32   /** 延迟启动 */
	Description string
}

const (
	AppInfoKey    = "AppInfo"
	APP_INFO_FILE = "/usr/share/appstart/config/AppInfo.json"
)

var AppInfoFile = `D:\Program Files\app\config\AppInfo.json`

type AppInfos []AppInfo

var Apps = AppInfos{
	// {Cmd: `C:\Program Files (x86)\Tencent\TIM\Bin\QQScLauncher.exe`, StartDelay: 1000, Description: "Tim"},
	// {Cmd: `C:\Program Files (x86)\Tencent\WeChat\WeChat.exe`, StartDelay: 1000, Description: "WeChat"},
	// {Cmd: `C:\Program Files (x86)\DingDing\DingtalkLauncher.exe`, StartDelay: 1000, Description: "Dingtalk"},
	// {Cmd: `C:\Foxmail 7.2\Foxmail.exe`, StartDelay: 1000, Description: "Foxmail"},
	// {Cmd: `C:\Users\28328\AppData\Local\youdao\dict\Application\YoudaoDict.exe`, StartDelay: 1000, Description: "YoudaoDict"},
}

func init() {
	if runtime.GOOS == "linux" {
		AppInfoFile = APP_INFO_FILE
	}
}

func main() {
	fmt.Println("----------app start-------------")

	file.ReadFile(filepath.Clean(AppInfoFile))
	// file.Write(Apps, AppInfoKey)
	file.Read(&Apps, AppInfoKey)

	Apps.Exec()
}

func (apps *AppInfos) Exec() {
	var ch = make(chan int, len(*apps))
	for i := 0; i < len(*apps); i++ {
		fmt.Println("app start: ", (*apps)[i].Cmd)
		cmd := exec.Command((*apps)[i].Cmd, (*apps)[i].Args...)
		go func(i int) {
			time.Sleep(time.Millisecond * time.Duration((*apps)[i].StartDelay))
			cmd.Start()
			ch <- i
		}(i)
	}

	for i := 0; i < len(*apps); i++ {
		<-ch
	}
}
